import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/common_req_utils.dart';
import 'package:yuan_hang_app/widget/w_text.dart';
import '../../../../base/base_state.dart';
import '../../../../http/api.dart';
import '../../../../bean/user.dart';
import '../../../../http/http_utils.dart';
import '../../../../res/w_constant.dart';
import '../../../../utils/common_utils.dart';
import '../../../../utils/router_helper.dart';
import '../../../../utils/string_utils.dart';
import '../../../../widget/label_item.dart';
import '../../../../widget/status_btn.dart';
import '../../../../widget/w_popup_window.dart';
import '../../../../widget/w_toast.dart';
import '../../model/book_manage_model.dart';
import '../order/order_model.dart';

class BookUpdatePage extends StatefulWidget {
  int bookId;
  String saleMan;

  BookUpdatePage({super.key, required this.bookId, required this.saleMan});

  @override
  BaseState<BookUpdatePage> createState() => _BookUpdatePageState();
}

class _BookUpdatePageState extends BaseState<BookUpdatePage> {
  final _formKey = GlobalKey<FormState>();
  List<Map> modelList =
      CommonReqUtils.getLabelListByKey(CommonReqUtils.carType);
  List<Map> appointType =
      CommonReqUtils.getLabelListByKey(CommonReqUtils.appointType);
  List<Map> saleManList = WConstant().salesmanList;

  List? timeSlots = [];
  List? filterTimeSlots = [];

  //初始化试驾预约登记对象
  Map bookInfo = {};
  bool isEdit = false;
  GlobalKey<LabelItemState>? remarkKey;
  GlobalKey<LabelItemState>? arriveDateKey;
  GlobalKey<LabelItemState>? appointTimeKey;
  GlobalKey<LabelItemState>? modelKey;
  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
        title: "预约修改",
        resizeToBottomInset: true,
        child: Column(children: [
          Expanded(
            child: SingleChildScrollView(
                padding: EdgeInsets.zero, child: _bookDriveItem()),
          ),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 10.px, vertical: 10.px),
            child: GestureDetector(
              onTap: () {
                print("修改的对象");
                print(bookInfo);
                //必填性校验,调用model的方法
                if (!BookManageModel.check(bookInfo)) {
                  return;
                }
                CommonUtils.throttle(updateBook);
              },
              child: Container(
                margin:
                    EdgeInsets.symmetric(vertical: 16.px, horizontal: 10.px),
                width: SizeUtils.screenW() - 48.px,
                alignment: Alignment.center,
                height: 48.px,
                decoration: BoxDecoration(
                  color: WColors.primaryColor,
                  borderRadius: BorderRadius.circular(24.px),
                ),
                child: WText(
                  "保存",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: WDimens.tsLarge,
                  ),
                ),
              ),
            ),
          ),
        ]));
  }

  void updateBook() {
    bool isUpdate = false;
    var salesman = {};
    if(int.tryParse(bookInfo["saleMan"]) == null){
      salesman = WConstant().salesmanList.firstWhere((item) => item['label'] == bookInfo["saleMan"]);
      isUpdate=true;
    }

    Map<String, dynamic> dataMap = {
      "id": widget.bookId,
      "remark": bookInfo["remark"],
      "modelId": bookInfo["modelId"],
      "arriveDate": StringUtils.safeGetValue(bookInfo["arriveDate"]).length<12? "${StringUtils.safeGetValue(bookInfo["arriveDate"])}00:00:00":bookInfo["arriveDate"],
      "appointTime": bookInfo["appointTime"],
      "saleMan":isUpdate?salesman["value"]:bookInfo["saleMan"],
      "resourceId":bookInfo["resourceId"]
    };

    String arriveDate =StringUtils.safeGetValue(bookInfo["arriveDate"] ).substring(0,10);
    DateTime nowTime= DateTime.now();
    String now = DateFormat('yyyy-MM-dd').format(nowTime);
    if(now.endsWith(arriveDate)){
      String endTimeStr = bookInfo["appointTime"].split("-").last.trim();
      String temp = "$arriveDate $endTimeStr:00";
      // 将字符串转换为DateTime对象
      DateTime givenDate = DateTime.parse(temp);
      if (givenDate.isBefore(nowTime)) {
        Toast.toast("预约时间不能小于当前时间");

        setState(() {
          bookInfo["appointTime"]="";
        });
        return;
      }
    }

    showLoading();
    HttpUtils().post(Api.testDriveBookingUpdate, data: dataMap).then((data) {
      hideLoading();
      if (data.resultCode == 200) {
        Toast.toast("预约修改成功");
        RouteHelper.maybePop(context, true);
      } else {
        Toast.toast(data.errMsg ?? "");
      }
    }).catchError((e) {
      hideLoading();
    });
  }

  Widget _bookDriveItem() {
    return Form(
        key: _formKey,
        child: Container(
            alignment: Alignment.center,
            margin: EdgeInsets.only(
                left: 16.px, right: 16.px, bottom: 10.px, top: 10.px),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10.px),
                color: Colors.white,
                boxShadow: const [
                  BoxShadow(
                      //线框阴影线条
                      color: WColors.CDFEFFB,
                      offset: Offset(0, 1),
                      blurRadius: 3)
                ]),
            child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  LabelItem(
                    label: "客户名称",
                    value: bookInfo["customerName"],
                    isEnabled: false,
                  ),
                  LabelItem(
                    value: bookInfo["phone"],
                    label: "手机号码",
                    isEnabled: false,
                  ),
                  LabelItem(
                      label: "预约类型",
                      value: CommonReqUtils.exchangeCodeToName2(
                          appointType, StringUtils.safeGetValue(bookInfo["appointType"])) ??
                          "-"
                  ),
                  LabelItem(
                      label: "车型",
                      value: CommonReqUtils.exchangeCodeToName2(
                          modelList, StringUtils.safeGetValue(bookInfo["modelId"]))??
                          "-"
                  ),
                  isEdit==true?
                    LabelItem(
                      labelType: LabelType.DROW_DOWN,
                      label: "接待顾问",
                      isMust: true,
                      isModel: true,
                      onSelected: (index) {
                        setState(() {
                          bookInfo["saleMan"] = index;
                        });
                      },
                      dataList: saleManList,
                    ):LabelItem(
                    label: "接待顾问",
                    isEnabled: false,
                    value: StringUtils.safeGetValue(widget.saleMan==""?CommonReqUtils.exchangeCodeToName2(saleManList, bookInfo["saleMan"]):widget.saleMan)
                  ),
                  LabelItem(
                    key: arriveDateKey,
                    label: "到店日期",
                    isMust: true,
                    labelType: LabelType.DATE,
                    minDateTime: DateTime.now(),
                    selectedDate: StringUtils.safeGetValue(bookInfo["arriveDate"]),
                    onDateChanged: (date) {
                      filterTimeSlot(date);
                      bookInfo["arriveDate"] = "$date 00:00:00";
                      bookInfo["appointTime"]="";
                      setState(() {});
                    },
                  ),
                  LabelItem(
                    label: "到店时间",
                    isMust: true,
                    labelType: LabelType.SELECT,
                    value: StringUtils.safeGetValue(bookInfo["appointTime"]),
                    onTap: (){
                      if(bookInfo["arriveDate"]==""){
                        Toast.toast("请先选择到店日期");
                        return ;
                      }
                      WPopupWindow.showBooKTime(dataList: filterTimeSlots??[],
                          context: context, bookInfo: bookInfo,onSelected: (info){
                            bookInfo = info;
                            setState(() {
                            });
                          });
                    },
                  ),
                  // GestureDetector(
                  //   onTap: () {
                  //     showTimeSlotBottomSheet(context);
                  //   },
                  //   child: LabelItem(
                  //     label: "到店时间",
                  //     isMust: true,
                  //     value: StringUtils.safeGetValue(bookInfo["appointTime"]),
                  //   ),
                  // ),
                  LabelItem(
                    key: remarkKey,
                    labelType: LabelType.TEXTAREA,
                    label: "备注",
                    isLast: true,
                    maxTextLength: 500,
                    onChanged: (text) {
                      setState(() {
                        bookInfo["remark"] = text;
                      });
                    },
                  ),
                ])));
  }

  void _printFormData() {
    //通过index获取code
    print("登记的对象是：$bookInfo");
  }


  void filterTimeSlot(String dateStr) {
    filterTimeSlots = [];
    DateTime selectDate = DateTime.parse(dateStr);
    DateTime today = DateTime.now();
    if (DateUtils.isSameDay(selectDate, today)) {
      for (int i = 0; i < timeSlots!.length; i++) {
        String endTimeStr = timeSlots![i]["timeRange"].split("-").last.trim();
        String temp = "$dateStr $endTimeStr:00";
        DateTime givenDate = DateTime.parse(temp);
        if (givenDate.isAfter(today)) {
          filterTimeSlots?.add(timeSlots![i]);
        }
      }
    } else {
      filterTimeSlots = timeSlots;
    }
  }

  Map<String, GlobalKey<LabelItemState>?> keyMap = {};

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    remarkKey = GlobalKey(debugLabel: "remark");
    arriveDateKey = GlobalKey(debugLabel: "arriveDate");
    appointTimeKey = GlobalKey(debugLabel: "appointTime");
    modelKey= GlobalKey(debugLabel: "modelKey");
    showLoading();
    //调用查询明细接口
    HttpUtils()
        .get("${Api.getTestDriveBookingDetail}/${widget.bookId}")
        .then((data) {
      hideLoading();
      if (data.resultCode == 200) {
        bookInfo = data.data;
        String arriveDate =StringUtils.safeGetValue(bookInfo["arriveDate"]).substring(0, 11);
        bookInfo["arriveDate"]=arriveDate;
        isEdit = StringUtils.safeGetValue(bookInfo["saleMan"])=="";
        setState(() {});
        remarkKey!.currentState?.refreshInput(bookInfo["remark"] ?? "");
        arriveDateKey!.currentState?.refreshDate(bookInfo["arriveDate"] ?? "");
        appointTimeKey!.currentState
            ?.refreshDate(bookInfo["appointTime"] ?? "");
        modelKey!.currentState
            ?.refreshList(modelList,bookInfo["modelId"] ?? "");
        ///调用时间预约查询你接口
        User user=WConstant().userInfo;
        ///新增预约的时候加载排版数据
        HttpUtils().get("${Api.getTestDriveTimeList}/${user.shopId}").then((data) {
          hideLoading();
          if (data.resultCode == 200) {
            timeSlots = data.data;
            setState(() {
              filterTimeSlot(arriveDate.trim());
            });
          }
        }).catchError((e) {
          hideLoading();
        });
      } else{
        Toast.toast(data.errMsg ?? "");
      }
    });


  }
}
